<?php
declare (strict_types=1);

namespace app\common\model;

use app\common\facade\Target;
use think\facade\Event;
use think\response\Json;

class User extends Base
{
    protected function level()
    {
        return $this->hasOne(Level::class, 'id', 'level_id');
    }

    protected function assets()
    {
        return $this->hasOne(Assets::class, 'uid');
    }

    protected function getActiveTimeAttr($value)
    {
        return $value ? date('Y-m-d H:i:s', intval($value)) : '未激活';
    }

    protected function getParentInfoAttr($value, $data)
    {
        $title = '-';
        if ($data['parent_id']) {
            $info = parent::where(['id' => $data['parent_id']])->find();
            $title = $info->code . '-' . $info->nickname . '-' . $info->mobile;
        }

        return $title;
    }

    public static function _save($param, $logs): array
    {
        parent::startTrans();
        try {
            if (isset($param['id']) && $param['id']) {
                $msg = '保存成功';
                $original = parent::where($logs['pk'], $param[$logs['pk']])->find();
                if (empty($original)) {
                    throw new \Exception('记录不存在，请检查！');
                }
                $is_mobile = parent::where(['mobile' => $param['mobile'], 'is_del' => 0])
                    ->where('id', '<>', $param['id'])->count();
                if ($is_mobile) {
                    throw new \Exception('手机号已存在');
                }
                $model = parent::update($param);
                $logs['original'] = $original;
                $logs['operation'] = 'save';
                if ($logs['writeLog']) {
                    $logs['model'] = $model;
                    Event::trigger('Logs', $logs);
                }
            } else {
                $msg = '注册成功';
                $parent = parent::where(['code' => $param['parent_code'], 'is_active' => 2, 'is_del' => 0])->find();
                if (!$parent) {
                    throw new \Exception('该邀请码不存在或未激活');
                }
                $param['code'] = generate();
                $param['parent_id'] = $parent->id;
                $param['password'] = md5($param['password']);
                $param['pay_password'] = md5($param['pay_password']);
                parent::create($param);
            }

            parent::commit();
        } catch (\Exception $e) {
            parent::rollback();

            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        return ['code' => 1, 'msg' => $msg, 'url' => url('login/index')->build()];
    }

    public static function _miniAppletSave($param): array
    {
        try {
            $info = parent::where(['openid' => $param['openid'], 'is_del' => 0])->find();
            $time = time();
            $ip = request()->ip();
            $token = md5(json_encode($param) . $param['openid'] . time());
            if ($info) {
                $info->token = $token;
                $info->last_ip = $ip;
                $info->last_time = $time;
                $info->save();
            } else {
                $data['token'] = $token;
                $data['openid'] = $param['openid'];
                $data['code'] = generate();
                $data['nickname'] = '微信用户-' . $data['code'];
                $data['mobile'] = $param['mobile'];
                $data['photo'] = '/static/admin/img/head_default.png';
                $data['password'] = md5('111111');
                $data['pay_password'] = md5('222222');
                $data['parent_id'] = $param['parent_id'];
                $data['parent_code'] = $param['parent_code'];
                $data['last_ip'] = $ip;
                $data['last_time'] = $time;
                parent::create($data);
            }

        } catch (\Exception $e) {

            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        return ['code' => 1, 'msg' => '登录成功', 'result' => ['token' => $token]];
    }

    public static function _miniAppletEdit($param, $user): array
    {
        parent::startTrans();
        try {
            if (!empty($param['nickname'])) {
                $user->nickname = $param['nickname'];
            }
            if (!empty($param['photo'])) {
                $user->photo = $param['photo'];
            }
            if (!empty($param['parent_code'])) {
                if ($user->parent_code) {
                    throw new \Exception('您已绑定过邀请码了');
                }
                $parent = parent::where(['code' => $param['parent_code'], 'is_active' => 2, 'is_del' => 0])->find();
                if (!$parent) {
                    throw new \Exception('邀请码不存在或未激活');
                }
                $user->parent_id = $parent->id;
                $user->parent_code = $parent->code;
                $res = Relation::generate($user->id, $user->code, $user->parent_id, $user->parent_code);
                if ($res !== true) {
                    throw new \Exception('绑定失败');
                }
            }
            $user->save();

            parent::commit();
        } catch (\Exception $e) {
            parent::rollback();

            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        return ['code' => 1, 'msg' => '操作成功'];
    }

    public static function onAfterInsert($user)
    {
        $user->assets()->save(['uid' => $user->id]);
        //记录推荐关系
        if ($user->parent_code) {
            Relation::generate($user->id, $user->code, $user->parent_id, $user->parent_code);
        }
    }

    public static function recharge($param, $admin): Json
    {
        parent::startTrans();
        try {
            $user = parent::find($param['id']);
            if ($user->isEmpty()) {
                throw new \Exception('未查询到相关会员');
            }
            $account = get_pay_way($param['account']);
            if ($param['mode'] == 1) {
                Target::Account()->basics($param['id'], $param['account'], $param['amount'], '后台充值', '+')
                    ->setMsg($param['remarks'])->createRecharge($admin['id']);
                $logs = '后台充值【' . $account . '】金额【' . $param['amount'] . '】会员【' . $user->code . '】';
            } else {
                Target::Account()->basics($param['id'], $param['account'], $param['amount'], '后台扣除', '-')
                    ->setMsg($param['remarks'])->createRecharge($admin['id']);
                $logs = '后台扣除【' . $account . '】金额【' . $param['amount'] . '】会员【' . $user->code . '】';
            }
            Logs::adds($logs, $admin['id'], $admin['admin_name']);

            parent::commit();
        } catch (\Exception $e) {
            parent::rollback();

            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }

        return json(['code' => 1, 'msg' => '操作成功']);
    }

    public static function security($param, $user, $first = false): array
    {
        try {
            $pass = $param['type'];
            $msg = '已设置';
            if (!$first) {
                if (md5($param['old_password']) != $user->$pass) {
                    throw new \Exception('原密码错误');
                }
                if (md5($param['old_password']) == md5($param['password'])) {
                    throw new \Exception('新密码与原密码一致，请更换');
                }
                $msg = '已修改';
            }
            $user->$pass = md5($param['password']);
            if ($pass == 'password') {
                $user->token = md5(time() . json_encode($user));
                cookie('token', null);
            }
            $user->save();

        } catch (\Exception $e) {

            return ['code' => -1, 'msg' => $e->getMessage()];
        }

        return ['code' => 1, 'msg' => $msg];
    }

    /**
     * 获取大小区业绩
     */
    public static function inviteSizeConsume($uid): array
    {
        $min_total = 0;
        $max_total = 0;
        $list = parent::where(['parent_id' => $uid, 'is_del' => 0])->order('total desc')
            ->column('my_total+team_total as total');
        if ($list) {
            $max_total = array_shift($list);
            if ($list) {
                $min_total = array_sum($list);
            }
        }

        return ['min_total' => $min_total, 'max_total' => $max_total];
    }

    /**
     * 判断一个会员是否在上级会员小市场
     */
    public static function maximumUser($uid, $relation_id)
    {
        $count = 0;
        $list = parent::where(['parent_id' => $uid, 'is_del' => 0])->order('total desc')
            ->column('id,my_total+team_total as total');
        if ($list) {
            array_shift($list);
            if ($list) {
                $childs = array_column($list, 'id');
                if (in_array($relation_id, $childs)) {
                    $count = 1;
                } else {
                    $count = Relation::whereIn('uid', $childs)->where(['new_uid' => $relation_id])->count();
                }
            }
        }

        return $count;
    }

    /**
     * 获取团队每条线上符合条件的条数
     */
    public static function getMarketCount($uid, $field, $level_id, $gs)
    {
        $list = parent::where(['parent_id' => $uid])->column('id');
        $market = 0;
        foreach ($list as $v) {
            $ids = Relation::where(['uid' => $v])->column('new_uid');
            $ids[] = $v;
            $count = parent::whereIn('id', $ids)->where($field, '>=', $level_id)
                ->where(['is_del' => 0])->count();
            if ($count >= $gs) {
                $market++;
            }
        }

        return $market;
    }
}